﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.UI;

namespace Xugege.AbpExtension.Core.Extension.File
{
    public class UploadFileManager : IUploadFileManager, ITransientDependency
    {

        private readonly IRepository<UploadFileRecord, long> _uploadFileRecordRepository;
        private readonly IAppFolderExtension _appFoldersExt;

        public UploadFileManager(
            IAppFolderExtension appFoldersExt,
            IRepository<UploadFileRecord, long> uploadFileRecordRepository)
        {
            _appFoldersExt = appFoldersExt;
            _uploadFileRecordRepository = uploadFileRecordRepository;
        }
        public async Task<IList<UploadFileRecord>> GetList(params Guid[] ids)
        {
            var results = await _uploadFileRecordRepository.GetAll().Where(m => ids.Contains(m.InstanceId))
                 .ToListAsync();
            return results;
        }
        /// <summary>
        /// 删除文件记录 并且同时删除数据库记录和物理磁盘记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task Remove(long id)
        {
            var temp = await GetAsync(id);
            string path = temp.RealPath;
            await _uploadFileRecordRepository.DeleteAsync(id);
            string fullpath = _appFoldersExt.WebRootPath + path;
            if (System.IO.File.Exists(fullpath))
            {
                System.IO.File.Delete(fullpath);
            }
        }

        public async Task<long> Add(UploadFileRecord file)
        {
            try
            {
                if (file.InstanceId == Guid.Empty)
                {
                    throw new Exception("参数错误");
                }
                return await _uploadFileRecordRepository.InsertAndGetIdAsync(file);
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        public async Task<UploadFileRecord> GetAsync(long id)
        {
            return await _uploadFileRecordRepository.GetAsync(id);
        }
    }
}
